import * as ACTION from '../../actions/fixup-work/conditionAction';
import merge from 'lodash/object/merge';
import assign from 'lodash/object/assign';
import cloneDeep from 'lodash/lang/cloneDeep';
import moment from 'moment';

const DATE_FORMATTER = 'YYYY-MM-DD';

let now = new Date, 
	last30days = moment(now).subtract(30, 'days').format(DATE_FORMATTER);
	now = moment(now).format(DATE_FORMATTER);

/**
 * 条件视图默认状态
 * @type {Object}
 */
export const DEFAULT_CONDITION_STATE = {
	// 是否正在请求筛选条件数据
	// isFilterFetching: false,
	// 省份(区域条件)
	province: '',
	// 城市(区域条件)
	city: '',
	// 区县(区域条件)
	county: '',
	// 学校(区域条件)
	school: '',
	// 学段条件, 默认勾选不限
	stage: ['-1'],
	// 年级条件, 默认勾选不限
	grade: ['-1'],
	// 学科条件, 默认勾选不限
	subject: ['-1'],
	// 用户特征条件
	userFeature: '0',
	// 版本条件
	version: '0',
	// 设备类型条件, 默认勾选不限
	deviceType: ['-1'],
	// 开始日期
	startDate: last30days,
	// 结束日期
	endDate: now,
	// 页面需要的可选数据
	dataOptions: {
		// 所有的省份
		province: [],
		provinceIsFetching: false,
		// 所有的城市
		city: [],
		cityIsFetching: false,
		// 所有的区县
		county: [],
		countyIsFetching: false,
		// 所有的学校
		school: [],
		schoolIsFetching: false,
		// 所有的学段
		stage: [],
		stageIsFetching: false,
		// 所有的年级
		grade: [],
		gradeIsFetching: false,
		// 所有的学科
		subject: [],
		subjectIsFetching: false,
		// 所有的版本
		version: [],
		versionIsFetching: false,
		// 所有的设备
		deviceType: [],
		deviceTypeIsFetching: false,
	}
}

/**
 * 条件视图Reducer
 * @param  {Object} state  当前状态
 * @param  {Object} action 当前Action
 * @return {Object}        新状态
 */
export function condition(state = DEFAULT_CONDITION_STATE, action = {}) {
	let { type } = action;

	switch(type) {
		// 初始化所有条件
		case ACTION.INIT_CONDITION_REQUEST: 
		{
			let { key } = action.payload;
			return merge({}, state, { dataOptions: { [`${key}IsFetching`]: true } });
		}
		// 初始化成功
		case ACTION.INIT_CONDITION_SUCCESS:
		{
			
			let { data, key } = action.payload;
			let dataOptions = cloneDeep(state.dataOptions);

			dataOptions[key] = data;
			dataOptions[`${key}IsFetching`] = false;

			return assign({}, state, { 
				// isFilterFetching: false, 
				dataOptions });
		}
		// 初始化失败
		case ACTION.INIT_CONDITION_FAILURE:
		{
			let { key } = action.payload;
			return merge({}, state, { dataOptions: {[`${key}IsFetching`]: false } });
		}
		// 设置keyPath描述的条件的值
		case ACTION.SET_CONDITION:
		{
			let { key, value } = action.payload, newState = {};

			if (!key) 
				throw new Error('在设置高级筛选条件时, 缺少条件键名');

			let dataOptions = cloneDeep(state.dataOptions);

			newState[key] = value;

			// 如果值为空, 则连附带的可选项也清除掉
			if (value === '')
				dataOptions[key] = [];
			
			return assign({}, state, newState, { dataOptions });
		}
		// 清除已选择条件
		case ACTION.CLEAR_CONDITION: 
			let dataOptions = cloneDeep(state.dataOptions);
			return assign({}, DEFAULT_CONDITION_STATE, { dataOptions });
		default:
			return state;
	}
}